﻿using System.Collections.Generic;
using UnityEngine;

public class StateMachineBase
{
    public  StateBase currentState { get; private set; }

    // 状态map
    protected Dictionary<string, StateBase> states;

    public StateMachineBase()
    {
        states = new Dictionary<string, StateBase>();
    }
    
    public virtual void Start()
    {
        currentState = GetState(Setting.idle);
        currentState.Enter();
    }
    
    //记录状态
    public virtual void AddState(StateBase state)
    {
        if (!states.ContainsKey(state.stateName))
        {
            states.Add(state.stateName, state);
        }
    }
    // 获取状态
    public  virtual StateBase GetState(string stateName)
    {
        if (states.ContainsKey(stateName))
        {
            return  states[stateName];
        }else
        {
            Debug.Log($"没有找到状态{stateName}");
            return null;
        }
    }

    public virtual void ChangeState(string stateName)
    {
        StateBase state = GetState(stateName);
        if (state != null)
        {
            currentState.Exit();
            currentState = state;
            currentState.Enter();
        }
    }

    public virtual void ChangeState(string stateName, object param)
    {
        StateBase state = GetState(stateName);
        if (state != null)
        {
            currentState.Exit();
            currentState = state;
            currentState.Enter(param);
        }
    }
    
    public virtual void Update()
    {
        currentState.Update();
    }
    
    //对比当前状态
    public virtual bool EqualCurState(string stateName)
    {
        return  currentState.stateName == stateName;
    }

    public virtual void TriggerFinish()
    {
        currentState.TriggerFinish();
    }

    public virtual void TriggerCancel()
    {
        currentState.TriggerCancel();
    }
    
    public virtual void OnDestroy()
    {
        foreach (var keyValuePair in states)
        {
            keyValuePair.Value.OnDestroy();
        }
    }
}